import {WordTips} from "../tips/WordTips";

export class WordsUtils {
  private static wordsTipPrefab: cc.Prefab = null;

  public static getPrefab() {
    return new Promise((resolve, reject) => {
      if (this.wordsTipPrefab) {
        return resolve(this.wordsTipPrefab)
      }
      cc.loader.loadRes('prefab/wordsTip', cc.Prefab, (err, prefab) => {
        if (err) {
          reject(err)
        } else {
          WordsUtils.wordsTipPrefab = prefab
          resolve(prefab)
        }
      })
    })
  }

  public static async showWords(text: string, type: TipsType) {
    const prefab = await this.getPrefab()
    const wordsNode = cc.instantiate(prefab)
    wordsNode.parent = cc.director.getScene()
    wordsNode.getComponent(WordTips).showText(text, type)

    function runAction(wordsNode: cc.Node) {
      wordsNode.runAction(cc.sequence([cc.delayTime(0.5), cc.moveTo(0.3, cc.v2(wordsNode.x, wordsNode.y + 20)), cc.callFunc(() => {
        wordsNode.destroy()
      })]))
      wordsNode.runAction(cc.sequence([cc.delayTime(0.5), cc.fadeOut(0.3)]))
    }

    runAction(wordsNode)
    return wordsNode
  }

  public static warn(text: string) {
    this.showWords(text, TipsType.WARN)
  }

  public static error(text: string) {
    this.showWords(text, TipsType.ERROR)
  }

  public static message(text: string) {
    this.showWords(text, TipsType.MESSAGE)
  }

  public static success(text: string) {
    this.showWords(text, TipsType.SUCCESS)
  }
}

window['xxx'] = WordsUtils

export enum TipsType {
  MESSAGE,
  WARN,
  SUCCESS,
  ERROR
}